package com.salemanagement.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.salemanagement.mapper.OrderMapper;
import com.salemanagement.service.OrderService;
import com.three.core.entity.Order;
import com.three.core.entity.ProductOrder;
import com.three.core.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class  MyListener {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "pt_queue01") //监听正常队列1分钟
    public void fund(Message message, Channel channel) {
        try {
            //判断微信的支付状态
            R<String> result = orderService.queryWeChatPayStatus(new String(message.getBody()));
            if (result.getCode() == 200) {
                //从正常队列删除该消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            } else {
                Thread.sleep(1000);//1秒
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        } catch (Exception e) {
            throw new AmqpRejectAndDontRequeueException(e.getMessage());
        }
    }


    @RabbitListener(queues = "dead_queue03") //监听死信队列
    public void dlxQueueMessage(Message message, Channel channel) {
        // byte[] body = message.getBody();
        String orderId = new String(message.getBody());
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderId);
        ProductOrder productOrder = orderMapper.selectOne(wrapper);//根据订单id查询数据库中订单状态
        if (productOrder != null) {
            // 查询订单的支付状态
            if ("11".equals(productOrder.getStatusCode()+"")) {
                // 将订单状态设置成已超时
                productOrder.setStatusCode(30); //超时
                this.orderMapper.updateById(productOrder);
                //修改库存数量
            }
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}